package com.example.demo.receiver;


import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import com.example.demo.beans.Messages;
import com.example.demo.util.ByteObj;



/**
 * 消息接收，并发送邮件
 * @author Administrator
 *
 */
@Component
public class HelloReceive {
	@Autowired
	private JavaMailSender mailSender;
	@Value("${mail.fromMail.addr}")
	private String from;
	//登录
	@RabbitListener(queues="topic.login")
	@RabbitHandler
	public void processA(String a) {
		SimpleMailMessage message = new SimpleMailMessage();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		String time = df.format(new Date());// new Date()为获取当前系统时间
		System.out.println(time);
		message.setFrom(from);
		message.setTo(a);
		message.setSubject("登录");
		message.setText("你与"+time+"登录");
		try {
			mailSender.send(message);
			System.out.println("简单邮件发送成功！");
		}catch (Exception e) {
			System.out.println("发送简单邮件时发生异常！"+e);
		}
    }
	//注册
	@RabbitListener(queues="topic.register")
	@RabbitHandler
	public void processB(String b) {
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(from);
		message.setTo(b);
		message.setSubject("注册");
		message.setText("欢迎注册");
		try {
			mailSender.send(message);
			System.out.println("简单邮件发送成功！");
		}catch (Exception e) {
			System.out.println("发送简单邮件时发生异常！"+e);
		}
        System.out.println("registerReceive接收:"+b);
    }
	//忘记密码
	@RabbitListener(queues="topic.forget")
	@RabbitHandler
	public void processC(byte [] by) throws Exception {
		Messages messages=(Messages)ByteObj.getObjectFromBytes(by);
		System.out.println("接受消息"+messages);
		String email = messages.getEmail();
		String randompwd = messages.getRandompwd();
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(from);
		message.setTo(email);
		message.setSubject("随机码");
		message.setText("你的随机登录密码为"+randompwd+"请前往登录");
		try {
			mailSender.send(message);
			System.out.println("简单邮件发送成功！");
		}catch (Exception e) {
			System.out.println("发送简单邮件时发生异常！"+e);
		}
       // System.out.println("forgetReceive接收:"+messages);
    }
}
